﻿using System;
using System.Globalization;
using System.Threading.Tasks;
using Windows.ApplicationModel;
using Windows.UI;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
using com.IronOne.BoardPACWinApp.Helpers;
using com.IronOne.BoardPACWinApp.View.Page;
using com.IronOne.BoardPACWinAppBO.Settings;
using com.IronOne.BoardPACWinAppService.Auth;
using com.IronOne.BoardPACWinAppService.Init;
using com.IronOne.BoardPACWinAppUtil.Enums;
using com.IronOne.BoardPACWinAppUtil.Util;

// The Settings Flyout item template is documented at http://go.microsoft.com/fwlink/?LinkId=273769

namespace com.IronOne.BoardPACWinApp.View.UserControl
{
    public sealed partial class GeneralSettingsFlyout
    {
        private IDialogService _dialogService;
        private AppSettingModel _model;
        private readonly IInitService _initService;
        private readonly IAuthService _authService;
        private readonly INavigationService _navigationService;
        public static bool IsFirstTime;

        public GeneralSettingsFlyout()
        {
            InitializeComponent();

            _navigationService = new NavigationService();
            _initService = new InitService();
            _authService = new AuthService();
            _dialogService = new DialogService();
        }

        private async void SettingsFlyout_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                _model = await _initService.ReadAppSettingsFromDb();

                var version = string.Format("{0}.{1}.{2}", Package.Current.Id.Version.Major,
                    Package.Current.Id.Version.Minor, Package.Current.Id.Version.Build);
                _model.AppVersion = version;

                if (_model.SyncFrequencyServerDecides <= 1)
                    _model.SyncFrequencyServerDecidesDisplay = "(Server: 1 Minute)";
                else
                    _model.SyncFrequencyServerDecidesDisplay = "(Server: " + _model.SyncFrequencyServerDecides +
                                                              " Minutes)";

                if (Global.UserId != 0) //user logged in
                {
                    var svrdateFormat = await _authService.GetSettingValueBySettingName(DatabaseType.UserDb, ApplicationConstants.UserDbSettingNames.dateOnlyFormat);
                    if (svrdateFormat != null && !String.IsNullOrWhiteSpace(svrdateFormat.ToString()))
                    {
                        var myDate = DateTime.ParseExact("1987-04-23", "yyyy-MM-dd", CultureInfo.InvariantCulture);
                        _model.DateFormatServerDecidesDisplay = "(Server: " + myDate.ToString(svrdateFormat.ToString()) + ")";
                    }
                }
                
                DataContext = _model;
                
                //NOTE: Windows 10 had issues with XAML Combobox SelectItem, so it was brought to code behind
                DateFormatsComboBox.SelectedItem = _model.DateFormatSelected;
                SyncFrequenciesComboBox.SelectedItem = _model.SyncFrequencySelected;
            }
            catch (Exception)
            {
            }
        }

        private async void SaveAndQuit_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                await SaveAndQuitCommon();
            }
            catch (Exception)
            {
            }
        }

        private async Task SaveAndQuitCommon()
        {
            try
            {
                var asm = (AppSettingModel) DataContext;

                //NOTE: Windows 10 had issues with XAML Combobox SelectItem, so it was brought to code behind
                asm.DateFormatSelected = (CustomKeyValuePair<string, string>) DateFormatsComboBox.SelectedItem;
                asm.SyncFrequencySelected = (CustomKeyValuePair<string, string>) SyncFrequenciesComboBox.SelectedItem;

                TxtServerUrl.BorderBrush = new SolidColorBrush(Colors.LightGray);
                asm.ServerUrl = asm.ServerUrl.Replace("\r\n", "");
                asm.ServerUrl = asm.ServerUrl.Replace("\r", "");
                asm.ServerUrl = asm.ServerUrl.Replace("\n", "");

                if (String.IsNullOrEmpty(asm.ServerUrl.Trim()))
                {
                    ResourceHandler.Get("err_100");
                    TxtServerUrl.Focus(FocusState.Keyboard);
                    TxtServerUrl.BorderBrush = new SolidColorBrush(Colors.Red);
                    //await _dialogService.ShowMessage(errMsg);
                    Show();
                    return;
                }
                if (!Uri.IsWellFormedUriString(asm.ServerUrl, UriKind.Absolute))
                {
                    ResourceHandler.Get("err_101");
                    TxtServerUrl.Focus(FocusState.Keyboard);
                    TxtServerUrl.BorderBrush = new SolidColorBrush(Colors.Red);
                    //await _dialogService.ShowMessage(errMsg);
                    return;
                }

                /*if (Global.UserId != 0) //User change settings after the login. So log him out first
                    await BasePage.GeneralSettingsButton_Click(_navigationService, _dialogService, _authService);

                if (Global.UserId == 0) //Loggedout
                {
                    asm.ServerUrl = asm.ServerUrl.TrimEnd('/');

                    await _initService.WriteAppSettingsToDb(asm);
                    this.Hide();                    
                }*/

                var result = true;
                if (Global.UserId != 0) //User change settings after the login. So log him out first
                    result =
                        await
                            _dialogService.ShowMessageYesNo("BoardPAC will restart. Are you sure?",
                                DefaultButtonCommand.No);

                if (result)
                {
                    //URL got changed. So reset the device to serve new server
                    var oldSettings = await _initService.ReadAppSettingsFromDb();
                    if (!oldSettings.ServerUrl.ToLower().Equals(asm.ServerUrl.ToLower()))
                    {
                        await _authService.ResetDevice();
                        IsFirstTime = true; //So on the next login user will display syncing msg while update new data from new server
                    }

                    //NOTE: This may take time so leave it like this without await
                    _authService.Logout();
                    await _initService.WriteAppSettingsToDb(asm);
                    Hide();
                    _navigationService.NavigateTo(typeof (SplashPage));
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        private void txt_ServerUrl_TextChanged(object sender, TextChangedEventArgs e)
        {
            TxtServerUrl.BorderBrush = new SolidColorBrush(Colors.LightGray);
        }

        private void SettingsFlyout_Unloaded(object sender, RoutedEventArgs e)
        {
            _dialogService = null;
            _model = null;
        }
    }
}